package com.beemans.corekit.ui.dialog;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewbinding.ViewBinding;

import com.beemans.corekit.integration.toolkit.LifecycleUtils;

public abstract class BaseDialogFragment<VB extends ViewBinding> extends DialogFragment {
    protected VB binding;
    protected FragmentActivity fragmentActivity;

    /**
     * 子类实现此方法，提供具体的 ViewBinding 对象
     */
    @Nullable
    protected abstract VB getViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container);

    protected void initData(@Nullable Bundle bundle) {
    }

    /**
     * 子类实现此方法，初始化视图和设置事件
     */
    protected abstract void initViews();

    /**
     * 初始化事件
     */
    protected void initEvents() {
    }

    /**
     * 加载数据
     */
    protected void loadData() {
    }

    /**
     * 初始化观察者
     */
    protected void initObverse() {
    }

    public BaseDialogFragment<VB> init(@NonNull FragmentActivity fragmentActivity) {
        this.fragmentActivity = fragmentActivity;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = getViewBinding(inflater, container);
        return binding != null ? binding.getRoot() : null;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initData(getArguments());
        initViews();
        initEvents();
        initObverse();
        loadData();
    }

    public void show() {
        if (fragmentActivity == null) {
            return;
        }

        LifecycleUtils.launchWhenResume(fragmentActivity, () -> {
            try {
                final String tag = this.getClass().getSimpleName();
                final FragmentManager manager = fragmentActivity != null ? fragmentActivity.getSupportFragmentManager() : null;
                if (manager == null) {
                    return;
                }
                final DialogFragment existingFragment = (DialogFragment) manager.findFragmentByTag(tag);
                if (existingFragment != null) {
                    manager.beginTransaction().remove(existingFragment).commitNow();
                }

                show(manager, tag);
            } catch (Throwable ignored) {
            }
        });
    }

    @Override
    public void dismiss() {
        if (fragmentActivity == null) {
            return;
        }

        LifecycleUtils.launch(fragmentActivity, () -> {
            try {
                dismissAllowingStateLoss();
            } catch (Throwable ignored) {
            }
        });
    }
}